package com.metaera.app.ui.activities;

import android.os.Bundle;
import android.view.MenuItem;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.jaeger.library.StatusBarUtil;
import com.metaera.app.R;
import com.metaera.app.controller.presenter.VersionUpdatePresenter;
import com.metaera.app.controller.view.VersionUpdateDialogView;
import com.metaera.app.ui.core.BaseActivity;
import com.metaera.app.ui.fragments.FlashNewsFragment;
import com.metaera.app.ui.fragments.HomeFragment;
import com.metaera.app.ui.fragments.MineFragment;
import com.metaera.app.utils.event.OnLauncherCalendarEvent;

import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends BaseActivity implements BottomNavigationView.OnItemSelectedListener{

    BottomNavigationView mBottomNavigation;

    final private Map<Integer, Fragment> mFragmentMap = new HashMap<>();


    @Override
    protected int getContentLayoutId() {

        return R.layout.activity_main;
    }

    @Override
    protected void initialize(Bundle savedInstanceState) {
        mBottomNavigation = findViewById(R.id.bottom_navigation);

        mBottomNavigation.setItemIconTintList(null);
        mBottomNavigation.setOnItemSelectedListener(this);

        // 初始化页面
        if (savedInstanceState != null) {
            restoreFragment(savedInstanceState);

        } else {
            mFragmentMap.put(R.id.nav_home, new HomeFragment());
            mFragmentMap.put(R.id.nav_flash_news, new FlashNewsFragment());
            mFragmentMap.put(R.id.nav_mine, new MineFragment());

            // 默认选中位置
            mBottomNavigation.setSelectedItemId(R.id.nav_home);
        }

        // 版本更新
        VersionUpdatePresenter presenter = new VersionUpdatePresenter();
        presenter.setModelAndView(new VersionUpdateDialogView(this));
        getLifecycle().addObserver(presenter);
        presenter.update();
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    // 恢复页面
    private void restoreFragment(Bundle savedInstanceState) {
        // 运势
        Fragment homeFragment = getSupportFragmentManager().getFragment(savedInstanceState, HomeFragment.class.getName());
        mFragmentMap.put(R.id.nav_home, homeFragment != null ? homeFragment : new HomeFragment());

        // 命书
        Fragment flashNewsFragment = getSupportFragmentManager().getFragment(savedInstanceState, FlashNewsFragment.class.getName());
        mFragmentMap.put(R.id.nav_flash_news, flashNewsFragment != null ? flashNewsFragment : new FlashNewsFragment());


        // 我的
        Fragment mineFragment = getSupportFragmentManager().getFragment(savedInstanceState, MineFragment.class.getName());
        mFragmentMap.put(R.id.nav_mine, mineFragment != null ? mineFragment : new MineFragment());

        // 选择
        mBottomNavigation.setSelectedItemId(savedInstanceState.getInt("SelectedItemId"));
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Fragment targetFragment = mFragmentMap.get(item.getItemId());

        if (targetFragment != null) {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            if (!targetFragment.isAdded()) {
                fragmentTransaction.add(R.id.content, targetFragment);
            }

            Set<Map.Entry<Integer, Fragment>> entries = mFragmentMap.entrySet();
            for (Map.Entry<Integer, Fragment> fragmentEntry : entries) {
                Fragment fragmentEntryValue = fragmentEntry.getValue();
                if (fragmentEntryValue == targetFragment) {
                    fragmentTransaction.show(fragmentEntryValue);
                } else {
                    fragmentTransaction.hide(fragmentEntryValue);
                }
            }

            fragmentTransaction.commit();
            return true;
        }

        return true;
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        Set<Map.Entry<Integer, Fragment>> entries = mFragmentMap.entrySet();
        for (Map.Entry<Integer, Fragment> fragmentEntry : entries) {
            Fragment fragment = fragmentEntry.getValue();
            if (fragment.isAdded()) {
                String key = fragment.getClass().getName();
                getSupportFragmentManager().putFragment(outState, key, fragment);
            }
        }

        // 选中的条目
        outState.putInt("SelectedItemId", mBottomNavigation.getSelectedItemId());
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void initStatusBar() {
        StatusBarUtil.setTranslucentForImageViewInFragment(this, 0, null);
        StatusBarUtil.setLightMode(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Subscribe
    public void event(OnLauncherCalendarEvent event){
        mBottomNavigation.setSelectedItemId(R.id.nav_flash_news);
        Fragment fragment = mFragmentMap.get(R.id.nav_flash_news);
        Bundle args = new Bundle();
        args.putInt("index", 1);
        if (fragment != null){
            fragment.setArguments(args);
        }
    }

}
